<template>
  <div>
    <el-table
      ref="multipleTable"
      :data="tableData"
      tooltip-effect="dark"
      style="width: 100%"
      @selection-change="changeCheck"
    >
      <!-- 复选框 -->
      <el-table-column type="selection" width="55"></el-table-column>
      <!-- 商品信息 -->
      <el-table-column label="商品信息" width="350" align="center">
        <template slot-scope="scope">
          <div class="demo-image__preview">
            <el-link @click="goToDetailPage(scope.row)">
              <el-image
                :src="scope.row.product.productImg"
                style="width: 100px; height: 100px"
              >
              </el-image>
            </el-link>
          </div>
        </template>
      </el-table-column>
      <!-- 单价 -->
      <el-table-column label="单价" width="80" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.product.price }}</span>
        </template>
      </el-table-column>
      <!-- 数量 -->
      <el-table-column
        prop="address"
        label="数量"
        align="center"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          <!-- 计数器 -->
          <el-input-number
            v-model="scope.row.preorderNum"
            controls-position="right"
            @change="
              (currentValue, oldValue) =>
                handleNumChange(currentValue, oldValue, scope.row)
            "
            @blur="handleBlur"
            :precision="0"
            :min="1"
          >
          </el-input-number>
        </template>
      </el-table-column>
      <!-- 移除购物车 -->
      <el-table-column label="操作" width="80" align="center">
        <template slot-scope="scope">
          <el-button
            type="danger"
            icon="el-icon-delete"
            @click="removeBookFromCart(scope.row)"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分割线 -->
    <el-divider></el-divider>
    <!-- 计算总价 -->
    <el-row :gutter="20" v-if="tableData.length">
      <el-col
        :span="3"
        style="margin-left: 70%; margin-top: 10px; font-size: large"
      >
        <span
          >总价：<span style="color: red">{{ showPay }}</span></span
        >
      </el-col>

      <!--订单编辑框-->
      <el-dialog
        :visible.sync="dialogVisible"
        title="编辑订单"
        @close="resetDialog"
      >
        <el-form :model="formData" ref="form">
          <el-form-item label="地址 ID" prop="addressId">
            <el-select
              v-model="formData.addressId"
              placeholder="请选择地址"
              clearable
            >
              <el-option
                v-for="address in addressList"
                :key="address.adrId"
                :label="address.acceptName + ' - ' + address.address"
                :value="address.adrId"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 商品信息 -->
          <el-form-item label="商品信息"
            ><br />
            <div
              v-for="(product, index) in selectedProducts"
              :key="index"
              class="product-info"
            >
              <span>{{ product.productName }}</span>
              <span>单价：{{ product.price }}</span>
              <span>数量：{{ product.preorderNum }}</span>
            </div>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="submitOrderfail">取消</el-button>
          <el-button type="primary" @click="submitOrder">确认</el-button>
        </div>
      </el-dialog>

      <!-- 提交按钮 -->
      <el-col :span="3">
        <div class="grid-content bg-purple">
          <el-button type="danger" @click="nowToBuy()">立即购买</el-button>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import axios from "axios";
import { jwtDecode } from "jwt-decode";

export default {
  name: "Cart",
  data() {
    return {
      paySum: 0, //记录当前选中的物品的总价
      tableData: [], //记录购物车信息
      dialogVisible: false,
      selectedProducts: [],
      formData: {
        addressId: "",
      },
      addressList: [], // 地址列表
      userId: "",
    };
  },
  mounted() {
    console.log("购物车信息：");
    this.getUserIdFromToken();
    this.findUserCart();
    this.fetchAddresses();
  },
  computed: {
    showPay() {
      return this.paySum.toFixed(2);
    },
  },
  methods: {
    // 获取用户 id
    getUserIdFromToken() {
      const token = localStorage.getItem("token");
      if (!token) {
        console.log("没有 token，跳转到登录页面");
        this.$router.push("/login");
        return;
      }

      try {
        console.log(token); // 输出获取到的token
        console.log(jwtDecode(token)); // 解析JWT并输出

        const decoded = jwtDecode(token); // 使用新的jwtDecode进行解析
        this.userId = decoded.userId; // 获取 userId
        console.log("用户ID:", this.userId);
      } catch (error) {
        console.error("Token 解码失败:", error);
      }
    },

    // 获取地址数据
    fetchAddresses() {
      axios
        .get("/address/getByUserId", {
          params: { userId: this.userId },
          headers: {
            "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
          },
        })
        .then((response) => {
          if (response.data.code === 200) {
            this.addressList = response.data.data; // 填充地址数据
          } else {
            console.error("获取地址失败", response.data.message);
          }
        })
        .catch((error) => {
          console.error("请求失败", error);
        });
    },

    //查询购物车信息
    findUserCart() {
      axios
        .post("/shoppingchart/searchById", {
          userId: this.userId,
        })
        // .then(function (response) { // 传统的 function 语法，这样会导致 this 指向发生变化，无法正确访问 Vue 实例的 tableData
        .then((response) => {
          // 使用箭头函数确保 this 的指向正确
          let books = response.data.data.shoppingCartList;
          console.log("购物车信息：");
          console.log(books);
          books.forEach((item) => {
            item.isCheck = false;
          });
          this.tableData = books;
        })
        .catch(function (error) {
          console.log(error);
        });
    },

    //处理购物车物品数量变化
    handleNumChange(currentValue, oldValue, row) {
      if (row.isCheck) {
        //重新计算待付款总额
        this.paySum =
          this.paySum + (currentValue - oldValue) * row.product.price;
      }
    },

    //处理计数器失焦
    handleBlur(v1, v2) {
      console.log(v1);
      console.log(v2);
    },

    //移除购物车某一物品
    removeBookFromCart(row) {
      let cartId = row.cartId;
      console.log("caedId", cartId);
      //发送移除信息给后端
      axios
        .post(
          "/shoppingchart/delete",
          {
            cartId: cartId,
          },
          {
            headers: {
              "Content-Type": "application/json", // 设置请求类型为 JSON
            },
          }
        )
        .then((res) => {
          console.log(res);
          if (res.data.code === 200) {
            if (res.data.data) {
              // isDel = true;
              // console.log(isDel);
              //根据处理结果table进行相应更新
              this.tableData = this.tableData.filter(
                (item) => item.product.productId != row.product.productId
              );
            }
          } else {
            //直接显示后端错误信息
            return this.$message.error(res.data.message);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },

    //计算当前选择需要支付的费用
    //复选框发生变化就会调该函数
    changeCheck(value) {
      let checks = [];
      value.forEach((item) => {
        checks.push(item.product.productId);
      });
      // console.log(checks);
      this.tableData.forEach((item) => {
        if (checks.indexOf(item.product.productId) >= 0) {
          item.isCheck = true;
        } else {
          item.isCheck = false;
        }
        // console.log(item);
      });
      this.paySum = 0;
      //选中待付款的书籍
      let selected = value;
      selected.forEach((item) => {
        console.log("item", item.product.price);
        this.paySum += parseInt(item.preorderNum) * item.product.price;
      });
      this.selectedProducts = value.map((item) => {
        return {
          ...item.product, // 复制 item.product 的所有属性
          preorderNum: item.preorderNum, // 添加 preorderNum 属性
          cartId: item.cartId,
        };
      });
    },

    //进入书籍详情页
    goToDetailPage(row) {
      // console.log(row);
      //获取书籍 id
      let product = row.product.productId;
      //前往商品详情页
      console.log("product", product);
      this.$router.push({
        path: "/product-detail",
        query: { productId: product },
      });
    },

    //立即购买
    nowToBuy() {
      this.dialogVisible = true;
    },
    resetDialog() {
      this.formData.addressId = ""; // Clear address ID
    },

    // 提交完成的订单
    submitOrder() {
      const orderData = this.selectedProducts.map((product) => ({
        cartId: product.cartId,
        productId: product.productId,
        userId: this.userId,
        preorderNum: product.preorderNum,
        product: {},
      }));

      if (!this.formData.addressId) {
        this.$message.warning("请选择地址后再付款！");
        return;
      }

      axios
        .post(
          `/shoppingchart/ShoppingCartToOrder?adr_id=${this.formData.addressId}&status=1`,
          orderData,
          {
            headers: {
              "Content-Type": "application/json", // 设置请求类型为 JSON
            },
          }
        )
        .then((response) => {
          if (response.data.code === 200) {
            this.$message.success("订单提交成功");
            this.selectedProducts.forEach((row) => {
              this.removeBookFromCart(row); // 调用移除购物车的方法
            });
            this.$router.push("/user-about/order"); // 跳转到订单列表页
          } else {
            this.$message.error(response.data.message);
          }
        })
        .catch((error) => {
          console.error("请求失败", error);
          this.$message.error("提交订单失败");
        });
    },

    // 提交失败的订单
    submitOrderfail() {
      const orderData = this.selectedProducts.map((product) => ({
        cartId: product.cartId,
        productId: product.productId,
        userId: this.userId,
        preorderNum: product.preorderNum,
        product: {},
      }));

      if (!this.formData.addressId) {
        this.$message.warning("请选择地址后再付款！");
        return;
      }

      axios
        .post(
          `/shoppingchart/ShoppingCartToOrder?adr_id=${this.formData.addressId}&status=0`,
          orderData,
          {
            headers: {
              "Content-Type": "application/json", // 设置请求类型为 JSON
            },
          }
        )
        .then((response) => {
          if (response.data.code === 200) {
            this.$message.success("订单提交成功");
            this.selectedProducts.forEach((row) => {
              this.removeBookFromCart(row); // 调用移除购物车的方法
            });
            this.$router.push("/user-about/order"); // 跳转到订单列表页
          } else {
            this.$message.error(response.data.message);
          }
        })
        .catch((error) => {
          console.error("请求失败", error);
          this.$message.error("提交订单失败");
        });
    },
  },
};
</script>

<style scoped>
el-table {
  width: 100%;
  height: 100%;
}
.product-info {
  display: flex;
  justify-content: space-between; /* 均匀分布 */
  align-items: center; /* 垂直居中对齐 */
  margin-bottom: 10px; /* 适当的底部间距 */
}

.product-info span {
  flex: 1; /* 每个 span 元素占据相等的宽度 */
  text-align: center; /* 让文本居中对齐 */
}
</style>
